<style lang="scss" scoped>
@import '../../assets/login.scss';
.tip {
	display: flex;
	justify-content: flex-start;
	align-items: center;

	div {
		display: inline-block;
		margin-right: 0.2rem;
	}
}
</style>

<template>
	<div class="login-container">
		<van-nav-bar title="注册" left-text="返回" left-arrow @click-left="$router.back()" />
		<van-form class="form" @submit="registerFn">
			<div class="form-item">
				<van-field v-model="form.mobile" label="手机号码" name="mobile" type="number" placeholder="请输入手机号码" size="large"
					:rules="[{ required: true }]" center clearable></van-field>
			</div>
			<div class="form-item">
				<van-field v-model="form.password" label="用户密码" name="password" type="password" placeholder="请输入密码"
					size="large" :rules="[{ required: true }]" center clearable></van-field>
			</div>
			<div class="form-item">
				<van-field v-model="form.repeatPassword" label="确认密码" name="repeatPassword" type="password"
					placeholder="请再次输入密码" size="large" :rules="[{ required: true, validator: validatorPassword }]" center
					clearable></van-field>
			</div>
			<div class="btn-box">
				<van-button type="default" color="#179AFE" :disabled="disabled" native-type="submit" block>注册
				</van-button>
				<div class="tip">
					<van-checkbox v-model="checked" icon-size="14px">
					</van-checkbox>
					<div>
						我已阅读并同意
						<router-link :to="{ name: 'Agreement' }">《服务协议》</router-link>
					</div>
				</div>
			</div>
		</van-form>
	</div>
</template>

<script>
import { isMobile } from '../../utils/validate';
import { register } from '../../api';

export default {
	name: 'Register',
	data() {
		return {
			form: {
				mobile: '',
				password: '',
				repeatPassword: '',
			},
			checked: true,
			isSending: false
		};
	},
	computed: {
		disabled() {
			return !this.checked || this.isSending === true;
		}
	},
	methods: {
		validatorPassword(val) {
			return this.form.password === this.form.repeatPassword;
		},
		async registerFn() {
			if (!isMobile(this.form.mobile)) {
				this.$toast('请输入正确手机号码!');
				return;
			} else {
				try {
					const regParams = {
						mobile: this.form.mobile,
						password: this.form.password,
					};
					this.isSending = true;
					const { code, message } = await register(regParams);
					if (code == 200) {
						this.$toast(message || '注册成功');
						this.$router.replace('/');
					} else {
						this.$toast(message);
					}
					this.isSending = false;
				} catch (error) {
					console.log(error);
					this.isSending = false;
				}
			}
		}
	}
};
</script>
